package org.cy.websocket.stomp.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.NonNull;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;

/**
 * Created in 2021-05-13 16:37
 *
 * @author cao.yong
 */
public class StompInboundChannel implements ChannelInterceptor {

    private static final Logger LOG = LoggerFactory.getLogger(StompInboundChannel.class);

    @Override
    public Message<?> preSend(@NonNull Message<?> message, @NonNull MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (null != accessor) {
            if (accessor.isHeartbeat()) {
                LOG.info("收到心跳消息: {}", accessor.getHeartbeat());
            } else if (StompCommand.CONNECT.equals(accessor.getCommand())) {
                LOG.info("用户 {} 已连接", accessor.getSessionId());
            } else if(StompCommand.DISCONNECT.equals(accessor.getCommand())) {
                LOG.info("用户 {} 已断开", accessor.getSessionId());
            } else if (StompCommand.SUBSCRIBE.equals(accessor.getCommand())) {
                LOG.info("用户订阅:{}", accessor.getDestination());
            }
        }
        return message;
    }
}
